const { ccclass, property } = cc._decorator;

@ccclass
class MatchEffectCtrl extends cc.Component {
    private effectParent: cc.Node = null;
    private targetParent: cc.Node = null;
    private targetItem: cc.Node = null;
    private isReady: boolean = false;
    private flyMailPool: cc.NodePool = new cc.NodePool("FlyMailPool");
    private flyMailPrefab: cc.Prefab = null;

    constructor() {
        super();
    }   

    static _instance:MatchEffectCtrl;
    public static getInstance(): MatchEffectCtrl {
        if (!this._instance) {
            this._instance = new MatchEffectCtrl();
        }
        return this._instance;
    }

    public setEffectEndPos() { }

    public ready(parent: cc.Node) {
        this.effectParent = parent;
        this.initMailPrefab();
        this.isReady = true;
    }

    public createFlyMail(startPos: cc.Vec2, endPos: cc.Vec2) {
        debugger
        let self = this;
        let flyMail = this.flyMailPool.size() > 0 ? this.flyMailPool.get() : cc.instantiate(this.flyMailPrefab);
        flyMail.parent = this.effectParent;
        flyMail.position = cc.v3(startPos,0);
        let controlPoint = cc.v2(startPos.x > endPos.x ? startPos.x - 100 : startPos.x + 100, startPos.y - 150);

        cc.tween(flyMail)
            .by(0.1, { y: 80 }, { easing: "backOut" })
            .delay(0.05)
            .bezierTo(0.2, startPos, controlPoint, endPos)
            .call(() => {
                self.destroyFlyMail(flyMail);
            })
            .start();
    }

    public initMailPrefab() {
        let self = this;
        cc.loader.loadRes("prefabs/flyMailPrefab", cc.Prefab, (error: any, prefab: cc.Prefab) => {
            if (!error) {
                self.flyMailPrefab = prefab;
            }
        });
    }

    public destroyFlyMail(flyMail: cc.Node) {
        this.flyMailPool.put(flyMail);
    }
}

export default MatchEffectCtrl.getInstance();